dofile (getScriptPath() .. "\\..\\processor\\processor.lua")
dofile (getScriptPath() .. "\\..\\processor\\log.lua")

dofile (getScriptPath() .. "\\..\\lib\\lib.lua")
dofile (getScriptPath() .. "\\..\\lib\\orders.lua")
dofile (getScriptPath() .. "\\..\\lib\\actions.lua")

script_name = string.gsub(string.gsub(debug.getinfo(1).short_src, "%.[^%.]*$", ""), "^.*[\\/]", "")

data = {
	delay = 3000,
}

processor:AddInit(function()
	if not lib:isConnected() then return true end
	client_code = lib:GetUser()
	script_id = client_code .. "#" .. script_name
	processor:InitLog(lib.path.log .. script_id .. ".log")
	processor:log("started")
end)


processor:AddInit(function()
	orders:AddOnLimitStopHandler()
end)

	
processor:AddTimer(function()
	data.limits = orders:GetLimits()
	local orders_hash = lib:tostring(data.limits) .. lib:tostring(orders:GetAllStops())
	
	if orders_hash ~= data.orders_hash then
		data.timer = lib:GetTime()
		data.orders_hash = orders_hash
	end
end)

	
processor:AddTimer(function()
	local pr, lock = orders:InProcess()
	if pr then
		data.timer = lib:GetTime()
		if lock then
			message("is locked")
		end
	end
end)

	
processor:AddTimer(function()
	if lib:IsDelay(data.timer, data.delay) then
		local codes = {}
		
		for _, order in pairs(data.limits) do
			--if orders:GetActivatedStop(order) then
			--	if order.qty ~= order.balance then
			--		codes[order.sec_code] = true	-- partly filled limit
			--	end
			--elseif not orders:GetActiveStops(order.sec_code, true)[1] then
			--	codes[order.sec_code] = true		-- take limit
			--end
			if order.qty ~= order.balance					-- partly filled limit
				or (not orders:GetActivatedStop(order)		-- not position limit
				and not orders:GetTakeLimitStop(order))		-- not take limit
			then
				codes[order.sec_code] = true
			end
		end
		
		for sec_code in pairs(codes) do
			--message("shift " .. sec_code)
			actions:Shift(sec_code)
		end
	end
end)

--[[	
processor:AddTimer(function()
	if not orders:InProcess() then
		processor:stop(0)
	end
end)
--]]

